<template>
  <el-select v-model="schoolCode" show-search allow-clear @change="onChange" placeholder="选择学校" clearable>
    <el-option v-for="item in schools" :key="item.code" :value="item.code" :label="item.code + ' ~ ' + item.name">
      {{ item.code }} ~ {{ item.name }}</el-option>
  </el-select>
</template>

<script>
import axios from "axios";

export default {
  name: "school-select-view",
  props: {
    value: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      schoolCode: this.value,
      schools: []
    };
  },
  watch: {
    value(newVal) {
      this.schoolCode = newVal;
    },
    schoolCode(newVal) {
      this.$emit('input', newVal);
    },
  },
  mounted() {
    this.queryAllSchool();
  },
  methods: {
    queryAllSchool() {
      axios.post("/rest/admin/school/list", { schoolCodeList: [] }, { headers: { 'Content-Type': 'application/json' } })
          .then((response) => {
            if (response.data.success) {
              this.schools = response.data.data;
            }
          })
          .catch(error => {
            console.error("Error fetching school data:", error);
          });
    },
    onChange() {
      let school = this.schools.find(item => item.code === this.schoolCode) || {};
      this.$emit('change', school);
    }
  },
};
</script>
